<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\admin\model;

use api\common\model\CommonModel;
use api\admin\model\BandToiletTagModel;

class BandToiletModel extends CommonModel
{
    // 可查询字段
    // protected $visible = [
    //     'id', 'start_time', 'end_time', 'man_num', 'woman_num','flow_num','titile','position','create_time',
    // ];
    //模型关联方法
    // protected $relationFilter = ['articles'];

    /**
     * 基础查询
     */
    // protected function base($query)
    // {
    //     $query->alias('BandToilet')->where('BandToilet.status', 1);
    // }
    /**
     * 关联
     * @return $this
     */
    // public function articles()
    // {
    //     return $this->belongsToMany('PortalPostModel','portal_tag_post','post_id','tag_id');
    // }

    /**
     * [getbandTag 获取绑定列表]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getbandTag($where = '')
    {
        return $this->alias("a")
            ->field('a.*,t.tag_name')
            ->join('band_toilet_tag t', 't.id = a.tag_id','LEFT')
            ->where($where)
            ->select();
    }


    /**
     * [dataInsertBand 插入绑定表]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function dataInsertBand($data = '', $tid = '',$master_mac = '')
    {

        $ids = [];
        $result = 0;
        $deviceType = [];
        $config = ['flow'=>1,'sensor'=>3,'smoke'=>4,'water'=>5,'electric'=>6,'sos'=>7,'wateryield'=>8];
        foreach ($data as $key => $value) {

            //数据为空跳出
            if (empty($value)) {
                continue;
            }
            // print_r($key);
            // echo "\n";
            $result = 1;
            //获取设备对应标识
            $type = (int)$config[$key];
            $deviceType[] = $type;
            //获取设备tag标识区分男女第三卫生间....
            foreach ($value as $k => $v) {

                $insert = [
                    'tag_id' => $v,
                    'mac' => '',
                    'mac_device_type' => $type,
                    't_id' => $tid,
                ];

                $where = $insert;
                unset($where['mac']);
                //查询是否存在该设备
                $exsit = $this->where($where)->find();
                if (!empty($exsit)) {
                    $ids[] = $exsit['id'];
                    continue;
                }else{
                    if ($master_mac) {
                        $insert['master_mac'] = $master_mac;
                    }
                    $result = $this->insert($insert);
                    $ids[] = $this->getlastInsID();
                }
            }

        }

        //删除多余数据

        if ($result) {

            $this->where([
                't_id' => $tid, 
                'mac_device_type' => ['IN',$deviceType],
                'id' => ['NOT IN',$ids]
            ])->delete();

        }

        return $result;

    }

    /**
     * [FunctionName description]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     */
    public function bandToMac($data = '', $master)
    {
        foreach ($data as $key => $value) {
            $value = $this->objectArray(json_decode(htmlspecialchars_decode(htmlspecialchars_decode($value))));
            $value['master_mac'] = $master;
            unset($value['tag_name']);
            $result[$key] = $value;
        }

        return $this->saveAll($result) ? 1 : 0;
    }

    // 对象转数组
    public function objectArray($array = '')
    {
        if (is_object($array)) {
            $array = (array) $array;
        }if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = $this->objectArray($value);
            }
        }
        return $array;
    }

    /**
     * [bandDevToMac 绑定红外设备]
     * @Author   HUI
     * @DateTime 2018-11-28
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function bandDevToMac($value, $tid, $type, $master, $bool = false,$tag_name)
    {
        $Tag = new BandToiletTagModel();
        foreach ($value as $k => $v) {
            $v = $this->objectArray(json_decode(htmlspecialchars_decode(htmlspecialchars_decode($v))));
            $tag_id = $Tag->getBandToiletTagFields(['tag_as_name'=>$tag_name],'id');
            unset($v['tag_name']);
            $insert = [
                'mac' => $v['mac'],
                'tag_id' => $tag_id['id'],
                't_id' => $tid,
                'byorder' => $v['byorder'],
                'mac_device_type' => $type,
                'master_mac' => $master,
            ];
            //
            if ($bool) {
                $insert['id'] = $v['id'];
            }
            $result[] = $insert;
        }
        return $this->saveAll($result) ? 1 : 0;
    }

    /**
     * [getBandToiletFields 获取单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function getBandToiletFields($id, $fields = '*')
    {
        if (is_array($id)) {
            return $this->field($fields)->where($id)->find();

        } else {
            return $this->field($fields)->where('id', $id)->find();
        }

    }

    /**
     * [getBandToiletFields 更新单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function updateBandToiletFields($id, $update = [])
    {

        if (is_array($id)) {
            return $this->where($id)->update($update);
        } else {
            return $this->where('id', $id)->update($update);
        }
    }

}
